package com.ylr.base.common.utils;

import com.ylr.base.common.po.user.UserPo;
import com.ylr.base.common.exception.YlrException;
import com.alibaba.fastjson2.JSON;

import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2023-04-21 15:33:57
 * className UserUtils 请求用户缓存工具类
 * version: 1.0
 * description:
 */
public class UserUtils {

    /**
     * 请求用户数据存储对象
     * 每个项目单独持有一份
     */
    private static final ThreadLocal<UserPo> threadLocal = new ThreadLocal<>();

    /**
     * 设置请求用户
     * @param user 用户基本数据对象
     */
    public static void setUser(UserPo user) {
        threadLocal.set(user);
    }

    /**
     * 设置请求用户
     * @param value 请求用户json对象
     */
    public static void setUser(String value) {
        UserPo userPo = JSON.parseObject(value, UserPo.class);
        threadLocal.set(userPo);
    }

    /**
     * 获取请求用户
     * @return 登录用户对象
     */
    public static UserPo getUser() {
        return threadLocal.get();
    }

    /**
     * 获取请求用户主键
     * @return 用户主键
     */
    public static Long getUserId() {
        UserPo userPo = getUser();
        if (Objects.isNull(userPo)) {
            throw new YlrException("请求用户为空");
        }
        return userPo.getId();
    }

    /**
     * 获取请求用户名称
     * @return 用户名称
     */
    public static String getUsername() {
        UserPo userPo = getUser();
        if (Objects.isNull(userPo)) {
            throw new YlrException("请求用户为空");
        }
        return userPo.getUsername();
    }

    /**
     * 清理请求用户
     */
    public static void deleteUser() {
        threadLocal.remove();
    }

}
